#include "seqlist.h"

seqlist * init_list(int cap)
{
    // 申请管理结构体
    seqlist *sqlist = malloc(sizeof(seqlist));
    if(sqlist == NULL)
    {
        perror("申请管理结构体失败");
        return NULL;
    }

    // 申请真正存储节点的顺序表空间
    sqlist->data = malloc(sizeof(student)*cap);
    if(sqlist->data == NULL)
    {
        perror("申请顺序表空间失败");
        free(sqlist);
        return NULL;
    }

    sqlist->capacity = cap;
    sqlist->len = 0;
    return sqlist;
}

bool is_full(seqlist *list)
{
    return list->len >= list->capacity;
}

bool add_list(const student *someone, seqlist *list)
{
    if(is_full(list))    
        return false;

    list->data[list->len] = *someone;
    list->len++;
    return true;
}

void list_for_each(seqlist *list)
{
    for(int i = 0; i < list->len; i++)
    {
        printf("姓名:%s, 年龄:%d, 分数:%.2f\n", list->data[i].name, list->data[i].age, list->data[i].score);
    }
}

void sort_list(seqlist *sqlist)
{
    bool flag = true;
    for(int i = 0; i < sqlist->len - 1; i++)
    {
        for(int j = 0; j < sqlist->len - 1 - i; j++)
        {
            if(sqlist->data[j].score > sqlist->data[j + 1].score)
            {
                flag = false;
                student tmp = sqlist->data[j];
                sqlist->data[j] = sqlist->data[j + 1];
                sqlist->data[j + 1] = tmp;
            }
        }
        if(flag)
            break;
    }
}

void destroy_list(seqlist *sqlist)
{
    if(sqlist->data != NULL){
        free(sqlist->data);
        sqlist->len = 0;
        sqlist->capacity = 0;
    }
    sqlist->data == NULL;
}